package com.github.data_manage.util

import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.DataFormatter
import org.springframework.util.StringUtils
import java.math.BigDecimal
import java.math.RoundingMode
import java.time.LocalDate

object ExcelUtils {

    fun getNumericCellValueFromCell(cell: Cell?): BigDecimal? {
        if (cell == null) {
            return null
        }
        return when (cell.cellType) {
            CellType.NUMERIC -> BigDecimal.valueOf(cell.numericCellValue)
            CellType.STRING -> cell.stringCellValue?.takeIf { StringUtils.hasText(it) }?.let { BigDecimal(it) }
            else -> null
        }?.setScale(4, RoundingMode.HALF_UP)
    }

    fun getFormatStringCellValueFromCell(cell: Cell?): String? {
        if (cell == null) {
            return null
        }
        val formatter = DataFormatter()
        return formatter.formatCellValue(cell)
    }

    fun getStringCellValueFromCell(cell: Cell?): String? {
        if (cell == null) {
            return null
        }
        return when (cell.cellType) {
            CellType.NUMERIC -> cell.numericCellValue.toString()
            CellType.STRING -> cell.stringCellValue
            else -> null
        }
    }


    fun getLocalDateCellValueFromCell(cell: Cell): LocalDate? {
        return when (cell.cellType) {
            CellType.STRING -> cell.stringCellValue?.takeIf { StringUtils.hasText(it) }
                ?.let { DateTimeUtils.tryParse(it) }

            CellType.NUMERIC ->
                cell.numericCellValue.toLong().let { return LocalDate.of(1900, 1, 1).plusDays(it) }

            else -> null
        }
    }

}
